﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FCDB.Entity;
using FCDB.Entity.EntityEx;
using FCDB.Repository;
using FCDB.Web.Models;
using FB.Mvc.Controllers;

namespace FCDB.Web.Controllers
{
       [FB.Membership.Annotations.AuthorizeOnly]
    public class WFProcessController : BaseController
    {
        //
        // GET: /WFProcess/
        private WFWorkFlowRepository respository = new WFWorkFlowRepository();

        public ActionResult Index()
        {
            long WorkFlowTypeID = 0;
            if (!string.IsNullOrEmpty(Request["typeId"]))
            {
                long.TryParse(Request["typeId"], out WorkFlowTypeID);
            }
            if (Request.IsAjaxRequest())
            { 
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip); 
                
                IList<WfProcessEx> list = respository.GetPagedList(skip, take, WorkFlowTypeID,"", out total);
                PagerModel model = new PagerModel()
                {
                    Data = list,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json; 
            }
            IList<WfProcessType> WorkFlowTypeList = respository.GetWorkFlowType( );
            ViewBag.WorkFlowTypeList = WorkFlowTypeList;
            return View();
        }
        public ActionResult Create()
        {
            WfProcess process = new WfProcess();
            IList<WfProcessType> WorkFlowTypeList = respository.GetWorkFlowType();
            IList<SelectListItem> list = new List<SelectListItem>(); 
            if(string.IsNullOrEmpty(Request["ID"]))
            {
                foreach (WfProcessType type in WorkFlowTypeList)
                {
                    SelectListItem item = new SelectListItem()
                    {
                         Value=type.ID.ToString(),
                         Text=type.Name
                    };
                    list.Add(item);
                }
                ViewData["ProcessTypeList"] = list;
                return View(process);
            }else
            {
                string id = Request["ID"];
                process = respository.GetProcess(new Guid(id));
                foreach (WfProcessType type in WorkFlowTypeList)
                {
                    SelectListItem item = new SelectListItem()
                    {
                        Value = type.ID.ToString(),
                        Text = type.Name,
                        Selected = type.ID == process.WfProcessTypeID
                    };
                    list.Add(item);
                }
                ViewData["ProcessTypeList"] = list;
                return View(process); 
            } 
        }
        public ActionResult Save(WfProcess model,  HttpPostedFileBase fXmlFile )
        {
             RtnMsg msg = new RtnMsg() { Status = 1 };
            if (model.ProcessGUID == new Guid("00000000-0000-0000-0000-000000000000"))
            {
                model.CreatedDateTime = DateTime.Now;
                model.LastUpdatedDateTime = DateTime.Now;
                model.Status = 1;  
                model.ProcessGUID = Guid.NewGuid();
                if(fXmlFile!=null)
                {
                    String xmlRootFolder = System.Web.HttpContext.Current.Server.MapPath("/ProcessXmlFolder");  // 获得RoomImgPath 的路径
                    string xmlfolder = Path.Combine(xmlRootFolder, model.WfProcessTypeID.ToString());  // 获存储文件夹的路径
                    if (!System.IO.Directory.Exists(xmlfolder))                                      //查看该文件夹存在不
                        System.IO.Directory.CreateDirectory(xmlfolder); 
                    model.XmlFilePath = model.WfProcessTypeID.ToString();                            
                    model.XmlFileName = fXmlFile.FileName; 
                    fXmlFile.SaveAs(Path.Combine(xmlRootFolder,model.XmlFilePath,model.XmlFileName ));  // 存储
                }
                respository.Add(model);
                return Json(msg);
            }
            else
            {
                WfProcess updateProcess = respository.GetProcess(model.ProcessGUID);
                updateProcess.ProcessName = model.ProcessName;
                updateProcess.PageUrl = model.PageUrl;
                updateProcess.WfProcessTypeID = model.WfProcessTypeID;
                updateProcess.Description = model.Description;
                updateProcess.LastUpdatedDateTime = DateTime.Now;
                if (fXmlFile != null)
                {
                      String xmlRootFolder = System.Web.HttpContext.Current.Server.MapPath("/ProcessXmlFolder");
                    //删除旧的配置文件
                      string path = Path.Combine(xmlRootFolder, updateProcess.XmlFileName, updateProcess.XmlFileName);
                    if(!string.IsNullOrEmpty(updateProcess.XmlFileName)&&System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }   
                    string xmlfolder = Path.Combine(xmlRootFolder, model.WfProcessTypeID.ToString());
                    if (!System.IO.Directory.Exists(xmlfolder)) System.IO.Directory.CreateDirectory(xmlfolder); 
                    updateProcess.XmlFilePath = model.WfProcessTypeID.ToString();
                    updateProcess.XmlFileName = fXmlFile.FileName;
                    updateProcess.WfProcessTypeID = model.WfProcessTypeID;
                    fXmlFile.SaveAs(Path.Combine(xmlRootFolder, updateProcess.XmlFilePath, updateProcess.XmlFileName)); 
                }
                respository.Update(updateProcess);
                return Json(msg);
            }  
        }
        public ActionResult Delete(string rpValue)
        {
            string[] ids = rpValue.Split(",".ToArray()); 
            foreach (string item in ids)
            { 
                if (!string.IsNullOrEmpty(item))
                {
                    WfProcess process = respository.GetProcess(new Guid(item));
                    process.Status = 2;
                    respository.Update(process);
                }
            }
            return null;
        }

    }
}
